<template>
  <div>
    <el-tabs model-value="first" type="card">
      <el-tab-pane label="因素权重" name="first">
        <div class="pl-40px pr-40px">
          <el-row>
            <template v-for="weight in weightData" :key="weight.id">
              <el-col :span="24">
                <div class="title">
                  <span>{{ weight.name }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="ml-50px mr-50px text-right">
                  <span>
                    <el-button type="primary" size="default" @click="edit(weight.id, weight.name)">
                      {{ weight.name }}编辑
                    </el-button>
                  </span>
                </div>
                <div class="p-20px pt-8px">
                  <el-table :data="weight.children" border>
                    <el-table-column prop="name" label="因素" align="center" />
                    <el-table-column prop="value" label="权重" align="center" />
                  </el-table>
                </div>
              </el-col>
              <el-col :span="8" />
              <el-col :span="8" />

              <template v-for="leave1 in weight.children" :key="leave1.id">
                <el-col :span="8" v-if="leave1.children && leave1.children.length">
                  <div class="ml-50px mr-50px text-right">
                    <span>
                      <el-button
                        type="primary"
                        size="default"
                        @click="edit(leave1.id, leave1.name)"
                      >
                        {{ leave1.name }}编辑
                      </el-button>
                    </span>
                  </div>
                  <div class="p-20px pt-8px">
                    <el-table :data="leave1.children" border>
                      <el-table-column prop="name" label="因素" align="center" />
                      <el-table-column prop="value" label="权重" align="center" />
                    </el-table>
                  </div>
                </el-col>
              </template>
            </template>
            <!-- <el-col :span="24">
              <div class="title">
                <span>二级指标权重</span>
              </div>
            </el-col>
            <template v-for="weight in weightData" :key="weight.name + 'weight'">
              <template v-for="leave1 in weight" :key="leave1.id">
                <el-col :span="6">
                  <div>
                    <div class="ml-50px mr-50px">
                      <span>{{ leave1.name }}</span>
                      <span class="float-right">
                        <el-button type="primary" link @click="edit(leave1.id, leave1.name)">
                          编辑
                        </el-button>
                      </span>
                    </div>
                    <div class="p-20px">
                      <el-table :data="leave1.children" border>
                        <el-table-column prop="name" label="因素" align="center" />
                        <el-table-column prop="value" label="权重" align="center" />
                      </el-table>
                    </div>
                  </div>
                </el-col>
              </template>
            </template>

            <el-col :span="24">
              <div class="title">
                <span>三级指标权重</span>
              </div>
            </el-col>
            <template v-for="weight in weightData" :key="weight.id + 'weight'">
              <template v-for="leave1 in weight" :key="leave1.id">
                <template v-for="leave2 in leave1.children" :key="leave2.id">
                  <el-col :span="8" v-if="leave2.children && leave2.children.length">
                    <div>
                      <div class="ml-50px mr-50px">
                        <span>{{ leave2.name }}</span>
                        <span class="float-right">
                          <el-button type="primary" link @click="edit(leave2.id, leave2.name)">
                            编辑
                          </el-button>
                        </span>
                      </div>
                      <div class="p-20px">
                        <el-table :data="leave2.children" border>
                          <el-table-column prop="name" label="因素" align="center" />
                          <el-table-column prop="value" label="权重" align="center" />
                        </el-table>
                      </div>
                    </div>
                  </el-col>
                </template>
              </template>
            </template> -->
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="修复技术评分" name="second">
        <ScoreEdit v-if="score.length" :score="score" :weightData="weightData" ref="scoreRef" />
      </el-tab-pane>
    </el-tabs>
    <div :span="24" class="text-center mt-16px">
      <el-button @click="cancel">上一步</el-button>
      <el-button type="primary" @click="next" :loading="formLoading">下一步</el-button>
    </div>
    <Matix ref="matixRef" @success="updateWeight" />
  </div>
</template>

<script setup lang="ts">
import { getWeight, getScore, updateScore } from '@/api/appraisal/index'
import Matix from './matix.vue'
import ScoreEdit from './score.vue'
import { ElMessageBox } from 'element-plus'
import { FormType } from '../types'

defineOptions({ name: 'Step4Form' })

const emits = defineEmits<{
  (e: 'next', data: any): void
  (e: 'cancel'): void
}>()

const { formRecord } = defineProps<{
  formRecord: FormType
}>()

const formLoading = ref(false)

/**
 * 获取权重列表
 */
const weightData = ref<any>()
const fetchWeight = async () => {
  const data = await getWeight()
  weightData.value = data
}
fetchWeight()

const matixRef = ref()
const edit = (id, title) => {
  matixRef.value.open(id, title)
}

/**
 * 更新权重
 */
const updateWeight = () => {
  fetchWeight()
}

/**
 * 获取评分
 */
const score = ref<any>([])
const fetchScore = async () => {
  const data = await getScore()
  score.value = data
}
fetchScore()

/**
 * 更新评分
 */
const updateListScore = (data) => {
  return new Promise(async (resolve) => {
    await updateScore(data)
    resolve(data)
  })
}

/**
 * 下一步
 */
const scoreRef = ref()
const next = async () => {
  formLoading.value = true
  score.value = scoreRef.value.submit()

  // 检查评分参数
  let isValid = true
  let errorTittle = ''
  score.value = scoreRef.value.submit()

  const keys = getChildrenKey(weightData.value).filter((item) => {
    return !['wrwlx', 'wrwnd'].includes(item)
  })
  score.value.forEach((item) => {
    if (!isValid) return
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      if (!/^\d+(\.\d+)?$/.test(item[key])) {
        isValid = false
        errorTittle = `${item.name} "${item}"`
        return false
      }
    }
  })

  if (!isValid) {
    ElMessageBox.alert(`${errorTittle} 评分设置无效、请重新设置`, '', {
      confirmButtonText: '确定',
      type: 'error'
    })
    formLoading.value = false
    return
  }
  await updateListScore(score.value)

  // 计算污染物特性评分
  score.value = score.value.map((item) => {
    return {
      ...item,
      ...calculate(item)
    }
  })

  formLoading.value = false
  emits('next', {
    score: score.value,
    weight: weightData.value
  })
}

// 获取所有叶子节点key
const getChildrenKey = (arr: any[]) => {
  let result: string[] = []
  for (let i = 0; i < arr.length; i++) {
    const data = arr[i]
    if (data.children && data.children.length) {
      const children = getChildrenKey(data.children)
      result = result.concat(children)
    } else {
      result.push(data.keyName)
    }
  }
  return result
}

// 计算特性子项评分
const calculate = (score) => {
  const keys = {
    wrwlx: ['zjs', 'wjw', 'fldVocs', 'ldVocs', 'fldSvocs', 'ldSvocs', 'syl'],
    wrwnd: ['yjwG', 'yjwZ', 'yjwD', 'wjwG', 'wjwZ', 'wjwD']
  }

  const weight = {
    zjs: 0,
    wjw: 0,
    ldVocs: 0,
    fldVocs: 0,
    ldSvocs: 0,
    fldSvocs: 0,
    syl: 0,
    yjwG: 0,
    yjwZ: 0,
    yjwD: 0,
    wjwG: 0,
    wjwZ: 0,
    wjwD: 0
  }

  const tableName = {
    重金属: 'zjs',
    无机物指标: 'wjw',
    '卤代VOCs\n': 'ldVocs',
    非卤代VOCs: 'fldVocs',
    卤代SVOCs: 'ldSvocs',
    非卤代SVOCs: 'fldSvocs',
    石油类: 'syl'
  }

  formRecord.interpolation.categorySums.forEach((item: any) => {
    const key = tableName[item.category]
    weight[key] = item.per * score[key]
  })

  formRecord.interpolation.groupResps.forEach((item: any) => {
    if (item.category === '无机物占比') {
      weight.yjwG = item.area2
      weight.yjwZ = item.area3
      weight.yjwD = item.area4
    }
    if (item.category === '无机物占比') {
      weight.wjwG = item.area2
      weight.wjwG = item.area3
      weight.wjwG = item.area4
    }
  })

  const setSouce = (keysArr) => {
    let total = 0
    keysArr.forEach((key) => {
      total += weight[key] * score[key]
    })
    return total
  }

  return {
    wrwlx: Number(setSouce(keys.wrwlx).toFixed(2)),
    wrwnd: Number(setSouce(keys.wrwnd).toFixed(2))
  }
}

/**
 * 上一步
 */
const cancel = () => {
  emits('cancel')
}
</script>

<style lang="scss" scoped>
// 标题样式
.title {
  position: relative;
  padding-left: 20px;
  margin-top: 30px;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  line-height: 30px;
  letter-spacing: 0.5px;
  color: var(--el-font-color-primary);

  &::before {
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: #50bfff;
    border-bottom-left-radius: 5px;
    border-top-left-radius: 5px;
    content: '';
  }
}
</style>
